const app = getApp()
Page({
  data: {
    homeButton: {
      name: 'home',
      isShow: true
    },
    phone: {
      name: 'phone',
      isShow: true
    },
    location: {
      name: 'location',
      isShor: true
    },
    longitude: null,
    latitude: null, // 经纬度
    merchant: [] // 商家地址
  },
  onLoad: function () {
    this.place(); // 位置的获取
  },
  place() { // 获取位置
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        this.NearTheShop(res.latitude,res.longitude); // 商家的位置获取
      }
    })
  },
  NearTheShop(latit,long){
    console.log(latit+"  "+long);
    var that = this
    wx.request({
      url: `http://localhost:8081/interfaced/shop/list?shopLongitude=${long}&shopLatitude=${latit}`,
      success(data){
        that.merchants(data.data.rows)
        console.log(data.data.rows);
      }
    })
  },
  merchants(data) {
    for (let a = 0; a < data.length; a++) {
      var m = this.getDistance(this.data.latitude, this.data.longitude, data[a].shopLatitude, data[a].shopLongitude)
      data[a].distance = m // 距离
    }

    this.setData({
      merchant: data
    })
  },
  gohome:function(){
    wx.navigateBack({
      delta:1
    })
  },
  dial() {
    wx.makePhoneCall({
      phoneNumber: '13562985018',
    })
  },
  // 计算距离函数
  Rad(d) {
    //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },
  getDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = (s*1000).toFixed(2) + 'm' //保留两位小数
    return s
  },
  order(data){ // 跳转到点单页面
    let name = data.currentTarget.dataset.name
    let index = data.currentTarget.dataset.inx
    let datas = {
      name : name, // 名称 
      latitude : this.data.merchant[index].latitude, 
      longitude : this.data.merchant[index].longitude, // 经纬度
      distance : this.data.merchant[index].distance // 距离
    }
    app.globalData.user.latitude = this.data.merchant[index].latitude
    app.globalData.user.longitude = this.data.merchant[index].longitude
    app.globalData.datas = datas
    wx.reLaunch({
      url:"../index/index?name=maps"
    })
  },
  retu(){
    wx.switchTab({
      url: '../homepage/index',
    })
  }
})